// 基础service类

import { Inject } from "@midwayjs/core";
import { Context } from "@midwayjs/koa";
import { FindManyOptions, FindOptionsWhere, Repository } from "typeorm";
import { arrToCamelCase } from "../utils";
// import CommonResponse from "./common.response";

export abstract class BaseService<T> {
  @Inject()
  ctx: Context

  abstract getModel(): Repository<T>;

  async create(entity: T) {
    return await this.getModel().save(entity);
  }

  async edit(entity: T): Promise<T | void> {
    return await this.getModel().save(entity);
  }

  async remove(entity: T) {
    await this.getModel().remove(entity);
  }

  async getById(id: string): Promise<T> {
    return await this.getModel()
      .createQueryBuilder('model')
      .where('model.id = :id', { id })
      .getOne();
  }

  async page(page: number, pageSize: number, where?: FindOptionsWhere<T>) {
    const order: any = { create_date: 'desc' };

    const [data, total] = await this.getModel().findAndCount({
      where,
      order,
      skip: (page - 1) * pageSize,
      take: pageSize,
    });

    return { data, total };
  }

  async list(where?: FindOptionsWhere<T> | FindOptionsWhere<T>[]) {
    const order: any = { create_date: 'desc' };
    const data = await this.getModel().find({
      where,
      order
    });

    return arrToCamelCase(data)
  }

  async getList(options?: FindManyOptions<T>) {
    const currentOpts = options || {};
    const defaultOrder: any = { create_date: 'desc' };
    const order = currentOpts?.order
    currentOpts.order = order ? Object.assign(order, defaultOrder) : defaultOrder;

    const data = await this.getModel().find(currentOpts);

    return arrToCamelCase(data)
  }
}